package com.py.article.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.py.article.mapper.ApArticleMapper;
import com.py.file.service.FileStorageService;
import com.py.model.article.pojos.ApArticle;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description TODO
 * @Author bo.li
 * @Date 2022/11/11 15:00
 * @Version 1.0
 */
@Service
public class ArticleDetailService {


    @Autowired
    Configuration configuration;

    @Autowired
    private FileStorageService fileStorageService;

    @Resource
    private ApArticleMapper articleMapper;


    public String createStaticHtml(String content, Long articleId) throws Exception {

        //获取模板
        Template template = configuration.getTemplate("article.ftl");
        //创建数据模型
        Map<String, Object> map = new HashMap<>();
        map.put("content", JSONArray.parseArray(content));

        //合成
        StringWriter out = new StringWriter();
        template.process(map, out);

        //把html文件上传到minio中
        ByteArrayInputStream in = new ByteArrayInputStream(out.toString().getBytes());
        String url = fileStorageService.uploadHtmlFile("", articleId + "html", in);

        //修改article文章表,保存静态文件url的位置
        ApArticle article = new ApArticle();
        article.setId(articleId);
        article.setStaticUrl(url);
        articleMapper.updateById(article);

        return url;
    }
}